<?php
/**
 * Created by PhpStorm.
 * User: wiggin
 * Date: 2017/11/3
 */

namespace App\Model;

use App\Utility\SysConst;
use Core\AbstractInterface\AbstractAsyncTask;
use Core\Component\ShareMemory;
use Core\Component\Logger;
use Core\Component\Di;


class Runner extends AbstractAsyncTask
{
    public $taskId = '';

    function handler(\swoole_server $server, $taskId, $fromId)
    {
        // TODO: Implement handler() method.
        //记录处于运行状态的task数量
        $share = ShareMemory::getInstance();
        $share->startTransaction();
        $share->set(SysConst::TASK_RUNNING_NUM, $share->get(SysConst::TASK_RUNNING_NUM) + 1);
        $share->commit();

        $taskList = Queue::getTaskList();
        if ($taskList && count($taskList)) {
            $task = $taskList[0];
            Logger::getInstance("task_info")->console("task_start:" . $task);
            $taskData = Queue::getTask($task, $taskId);
            $return = array();
            if ($taskData) {
                $taskData = unserialize($taskData);
                if (!empty($taskData['task_bean'])) {  //这里还可以增加更加灵活的处理,应该可以支持多种处理方式
                    $obj = Di::getInstance()->get($taskData['task_bean']);
                    if ($obj) {
                        $return = $obj->handler($taskData);
                    }
                }
            }
            Logger::getInstance("task_info")->console("task_data_num:" . count($return));
            Queue::endTask($taskId);
            Logger::getInstance("task_info")->console("task_end:" . $task);
        }
        /*$task = Queue::pop();
        if ($task instanceof TaskBean) {
            $req = new Request($task->getUrl());
            $ret = $req->exec()->getBody();
            sleep(20);
            Logger::getInstance("curl")->console("finish url:" . $task->getUrl());
        }*/
        //while其实为危险操作，while会剥夺进程控制权
        /*while (true) {

        }*/
//        Logger::getInstance()->console("async task exit");
        $share->startTransaction();
        $share->set(SysConst::TASK_RUNNING_NUM, $share->get(SysConst::TASK_RUNNING_NUM) - 1);
        $share->commit();
    }

    function finishCallBack(\swoole_server $server, $task_id, $resultData)
    {
        // TODO: Implement finishCallBack() method.
    }
}